<template>
	<el-upload ref="upload" multiple :action="uploadImgUrl" :on-success="handleUploadSuccess" :headers="uploadHeader" :accept="uploadAccept"
		:before-upload="handleBeforeUpload" :on-error="handleUploadError" :data="uploadParams" class="multiple_file_upload">
		<el-button type="primary" icon="el-icon-upload2">上传文件</el-button>
		<div slot="tip" class="tips">
			<label>建议：上传文件</label>
			<span v-if="!!size">大小不超过{{size}}MB</span>
			<span v-if="!!size && !!accept">且</span>
			<span v-if="!!accept">格式为{{accept}}</span>
		</div>
	</el-upload>
</template>

<script>
import { mapGetters } from 'vuex';
export default {
	name: 'swFileUploader',
	props: {
		value: { type: Array, default: () => [] },
		// 文件大小, 例如['png', 'jpg', 'jpeg']
		size: { type: String, default: '1000' },
		// 文件类型, 例如['png', 'jpg', 'jpeg']
		accept: { type: String, default: '' },
		//上传类型
		type: { type: String, default: '3' }
	},
	data() {
		let baseURL = !window.baseUrl ? process.env.VUE_APP_BASEURL : window.baseUrl;
		return {
			fileList: this.value,
			uploadImgUrl: `${baseURL}tbSysAttachment/upload`, // 上传的图片服务器地址
			uploadParams: { showType: '1', type: this.type }
		};
	},
	watch: {
		value(arr) {
			console.log(arr);
			this.fileList = arr;
		},
		fileList(arr) {
			this.$emit('input', arr);
		}
	},
	computed: {
		...mapGetters(['token']),
		uploadAccept() {
			let suffixArr = this.accept.split(',').map((item) => '.' + item);
			return suffixArr.join();
		},
		uploadHeader() {
			return { Authorization: this.token }
		}
	},
	methods: {
		//修改上传
		handleAmendUpload() {
			this.$refs['upload'].$el.querySelector('.uploadBtn').click();
		},

		// 删除图片
		handleDeleteImage() {
			this.imageId = '';
			this.imageUrl = '';
		},

		//预览图片
		handlePreviewImage() {
			this.$refs['preview'].clickHandler();
		},

		// 上传前loading加载
		handleBeforeUpload(file) {},

		// 文件个数超出
		handleExceed() {
			this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`);
		},

		// 上传成功回调
		handleUploadSuccess(res, file) {
			if(res.code == '0') {
				let datas = !res.data ? {} : res.data[0];
				this.imageId = datas.id;
				this.imageUrl = datas.originalAddr;
			}
		},

		// 上传失败
		handleUploadError() {
			this.$modal.msgError('上传图片失败，请重试');
			this.$modal.closeLoading();
		}
	}
};
</script>

<style lang="scss" scoped>
.multiple_file_upload::v-deep {
	.tips {
		color: #999;
		line-height: 20px;
		margin-top: 10px;
	}
}
</style>